package com.tandashi.springbootstudy01.config;

import com.tandashi.springbootstudy01.entity.user.LoginUser;
import com.tandashi.springbootstudy01.entity.user.WechatUser;
import com.tandashi.springbootstudy01.service.study.StudyContext;
import com.tandashi.springbootstudy01.service.user.WeChatUserService;
import com.tandashi.springbootstudy01.util.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.naming.AuthenticationException;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Slf4j
public class StudyAuthFilter implements Filter {

    @Autowired
    private WeChatUserService weChatUserService;

    @Override
    public void init(FilterConfig filterConfig){

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain){
        try {
            checkPermission(request);

            chain.doFilter(request,response);
        } catch (Throwable e) {
            try {
                //it may cause an exception and result in skipping the finally block.
                //so we warp it within a try-catch block.
                response.setCharacterEncoding("UTF-8");
                response.getWriter().println("{\"errCode\":10008,\"errMsg\":\"请登录!\"}");
            }catch (Throwable ignore){
            }
        }finally {
            StudyContext.remove();
        }
    }

    private void checkPermission(ServletRequest request) {
        HttpServletRequest req = (HttpServletRequest)request;
        ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(req.getSession().getServletContext());
        if(ctx != null && ctx.getBean("weChatUserServiceImpl") != null && weChatUserService == null){
            weChatUserService = (WeChatUserService) ctx.getBean("weChatUserServiceImpl");
        }

        log.info("StudyAuthFilter weChatUserService:{}",weChatUserService);


        String token = getToken(req);
        LoginUser user = decrypt(token);

        WechatUser weChatUser = weChatUserService.findWeChatUser(user.getUnionid());
        if(weChatUser == null){
            throw new RuntimeException("user is not exist");
        }

        StudyContext.set(user);
        request.setAttribute(CUSTOMER_ID,user.getCustomerId());
    }

    private LoginUser decrypt(String token) {
        return JWTUtils.decode(token);
    }

    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(TOKEN);
        return Objects.requireNonNull(token);
    }

    @Override
    public void destroy() {

    }

    private static final String TOKEN = "token";
    private static final String CUSTOMER_ID =   "customerId";
}
